package com.xykj.enterprise.wechat.busi.api.identity;

import com.xykj.enterprise.wechat.bean.ext.identity.GetPermanentCodeVo;
import com.xykj.enterprise.wechat.busi.config.ExtClient;
import com.xykj.enterprise.wechat.busi.service.sys.SysParamService;
import com.xykj.enterprise.wechat.busi.service.corp.CorpService;
import com.xykj.enterprise.wechat.busi.service.identity.SuiteTicketService;
import com.xykj.enterprise.wechat.util.Const;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhouxu
 * @create 2021-03-29 22:15
 */
@Function(description = "生成企业微信-企业永久授权码", parameters = {
        @Parameter(name = "suite_id", type = Type.String, description = "以ww或wx开头应用id（对应于旧的以tj开头的套件id", required = true),
        @Parameter(name = "auth_code", type = Type.String, description = "临时授权码", required = true),
        @Parameter(name = "suite_id", type = Type.String, description = "suite_id", required = true),
        @Parameter(name = "secret", type = Type.String, description = "secret", required = true),

})
@Component
@Slf4j
public class GeneratePermanentCode implements Action {

    @Autowired
    private SuiteTicketService suiteTicketService;
    @Autowired
    private ExtClient extClient;
    @Autowired
    private CorpService corpService;

    @Override
    public Response execute(Request request) throws Exception {
        String suiteId = request.getString("suite_id");
        try {
            Map params = new HashMap();
            params.put("suite_id",suiteId );
            params.put("suite_secret", request.getString("secret"));
            params.put("suite_ticket", suiteTicketService.getLatest(suiteId).getSuitTicket());
            params.put("auth_code", request.getString("auth_code"));

            GetPermanentCodeVo getPermanentCodeVo = extClient.get("GetPermanentCodeVo", params, GetPermanentCodeVo.class);
            // 存储永久授权码
            corpService.save(getPermanentCodeVo);
            // 初始化企业扩展信息
            corpService.initExtInfo(getPermanentCodeVo.getAuth_corp_info().getCorpid());
            return Response.success();
        }catch (Exception e){
            log.error("生成企业微信-企业永久授权码失败",e);
            return Response.fail(e);
        }

    }
}
